"use strict";

import axios from "axios";
import {ElMessageBox, ElMessage} from 'element-plus';
import router from '../router/index';
import store from '../store/index';
import Cookie from "js-cookie";

const DEBUG = true;
let baseURI = '';
if (DEBUG) {
    baseURI = 'http://ink.test/index/';
} else {
    baseURI = 'http://api.moyuu.cn/index/';
}

let config = {
    baseURL: baseURI,
    withCredentials: true,
    timeout: 60 * 1000, // Timeout
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
    config => {
        config.headers['authorization'] = 'Bearer ' + store.getters.getToken;
        config.headers['timestamp'] = parseInt(new Date().getTime()/1000);
        config.headers['token'] = 'f6dde5337580e6d1ea575ce657ff2dde';
        config.headers['lang'] = store.getters.getUserInfo.lang ?store.getters.getUserInfo.lang :'zh-cn';
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// Add a response interceptor
_axios.interceptors.response.use(
    function (response) {
        if (response.status !== 200) {
            return Promise.reject(new Error(res.message || "Error"));
        }else if(response.data.code == undefined){
            return response;
        }
        const res = response.data;
        if (res != undefined) {
            if (res.code == 403) {
                ElMessageBox.alert('令牌失效，请重新登录', '警告', {
                    callback: action => {
                        localStorage.removeItem('token');
                        Cookie.remove('uuid');
                        Cookie.remove('sid');
                        Cookie.remove('rid');
                        Cookie.remove('token');
                        router.push({
                            name: 'Login'
                        });
                    }
                });
                return Promise.reject(response);
            } else if (res.code == 1) {
                if(res.message != ''){
                    ElMessage.success({
                        message: res.message,
                        type: 'success'
                    })
                }
            } else {
                ElMessage.error(res.message);
                return Promise.reject(response);
            }
        }
        return response;
    },
    function (error) {
        // Do something with response error
        return Promise.reject(error);
    }
);


export default _axios;
